using System;
using System.Collections.Generic;
using System.Linq;
using Sedge.Core.Configuration;
using Sedge.Core.Execution;
using Sedge.Core.FileSystemWrap;
using Sedge.Core.Globalization;
using Sedge.Core.Utils;
using Microsoft.Test.CommandLineParsing;

namespace Sedge.Core.App
{
	public class Bootstrapper
	{
		public void Run()
		{
			Services.ViewManager = new ViewManager();
			Services.FileSystem = new FileSystem();

			//Locale.SaveCurrent("lang.current");
			//Locale.SaveCurrentTemplate("langTemplate.current");
			string[] arguments = Environment.GetCommandLineArgs();
			CommandLineParams clp = ParseCommandLine(arguments.Skip(1));
			AppConfiguration appConfiguration = ParseAppConfig(Services.FileSystem.Path.GetDirectoryName(arguments[0]));

			SuiteFinderOptions finderOptions = SuiteFinderOptions.Compose(clp, appConfiguration);
			Suite suite = SuiteFinder.GetSuite(finderOptions);

			if (suite != null)
			{
				ScheduleRunner scheduleRunner = new ScheduleRunner(suite);
				scheduleRunner.Run(clp.Silent);
			}
			else
			{
				ErrorHandler.Error(Locale.Strings.ESuiteNotFound, appConfiguration.DefaultFolder);
			}
		}

		private static CommandLineParams ParseCommandLine(IEnumerable<string> arguments)
		{
			CommandLineParams clp = new CommandLineParams();
			try
			{
				clp.ParseArguments(arguments);
			}
			catch
			{
				ErrorHandler.Error(Locale.Strings.EInvalidParameter);
			}

			return clp;
		}

		private static AppConfiguration ParseAppConfig(string defFolder)
		{
			AppConfiguration appConfiguration = new AppConfiguration();

			try
			{
				appConfiguration.DefaultSuite = System.Configuration.ConfigurationManager.AppSettings["DefaultSuite"];
				appConfiguration.DefaultApplication = System.Configuration.ConfigurationManager.AppSettings["DefaultApp"];
				appConfiguration.DefaultFolder = System.Configuration.ConfigurationManager.AppSettings["SearchFolder"];

			}
			catch (Exception)
			{
				appConfiguration.DefaultSuite = String.Empty;
				appConfiguration.DefaultApplication = String.Empty;
			}

			if (String.IsNullOrEmpty(appConfiguration.DefaultFolder))
				appConfiguration.DefaultFolder = defFolder;
			return appConfiguration;
		}
	}
}